/**
 * Created by xiang on 03/04/2017
 */
const extend = function (dest, source) {
  for (let obj in source) {
    if (source.hasOwnProperty(obj) && source[obj] !== null) {
      dest[obj] = source[obj];
    }
  }
  return dest;
};

const dateFormat = function (date, fmt = 'yyyy-MM-dd') {
  if (!(date instanceof Date)) {
    date = new Date(date);
  }
  let o = {
    "M+": date.getMonth() + 1,                 //月份
    "d+": date.getDate(),                    //日
    "h+": date.getHours(),                   //小时
    "m+": date.getMinutes(),                 //分
    "s+": date.getSeconds(),                 //秒
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度
    "S": date.getMilliseconds()             //毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (let k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    }
  }
  return fmt;
};

const renderLatexFromString = function (content, option) {
  let elem = document.createElement('div');
  elem.innerHTML = content;
  let opt = {
    delimiters: [
      {left: "$$", right: "$$", display: true},
      {left: "$", right: "$", display: false}
    ]
  };
  renderMathInElement(elem, extend(opt, option));
  return elem;
};

const renderMathInParent = function(text, parentClassName) {
  let elem = renderLatexFromString(text);
  let parentElem = document.getElementsByClassName(parentClassName)[0];
  parentElem.innerHTML = '';
  parentElem.appendChild(elem);
  return elem;
};

const renderLatex = function (elem, option) {
  let opt = {
    delimiters: [
      {left: "$$", right: "$$", display: true},
      {left: "$", right: "$", display: false}
    ]
  };
  renderMathInElement(elem, extend(opt, option));
  return elem;
};

/**
 * 转换成url的查询参数
 */
const toUrlQuery = function (params) {
  let queries = [];
  for(let key in params){
    if(params.hasOwnProperty(key)){
      queries.push(key+'='+params[key]);
    }
  }
  return queries.join('&');
};

export default {
  extend,
  dateFormat,
  renderLatex,
  renderLatexFromString,
  renderMathInParent,
  toUrlQuery
}
